package com.test.very.quick.demo;

import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.support.RetryTemplate;

@Configuration
public class RabbitConfiguration {

    private static final String QUEUE_NAME = "my-config-queue";


    /**
     * @Author: zss
     * @Date: 2018/7/12 下午5:07
     * @Description: 声明一个消息队列连接工厂
     */
    @Bean
    public ConnectionFactory connectionFactory() {
        //消息队列host／port
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory("127.0.0.1", 5672);
        //消息队列账户
        connectionFactory.setUsername("zss");
        //消息队列密码
        connectionFactory.setPassword("zss");
        //消息队列服务所需虚拟机
        connectionFactory.setVirtualHost("/zss");
        return connectionFactory;
    }

    /**
     * @Author: zss
     * @Date: 2018/7/12 下午5:53
     * @Description:
     */
    @Bean
    public AmqpAdmin amqpAdmin() {
        return new RabbitAdmin(connectionFactory());
    }

    /**
     * @Author: zss
     * @Date: 2018/7/12 下午5:53
     * @Description: 声明已消息队列模版并添加重试功能
     */
    @Bean
    public RabbitTemplate rabbitTemplate() {
//        return new RabbitTemplate(connectionFactory());
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        RetryTemplate retryTemplate = new RetryTemplate();
        ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
        backOffPolicy.setInitialInterval(500);
        backOffPolicy.setMultiplier(10.0);
        backOffPolicy.setMaxInterval(10000);
        retryTemplate.setBackOffPolicy(backOffPolicy);
        template.setRetryTemplate(retryTemplate);
        return template;
    }


    /**
     * @Author: zss
     * @Date: 2018/7/12 下午5:53
     * @Description: 声明一个消息队列
     */
    @Bean
    public Queue myQueue() {
        return new Queue(QUEUE_NAME);
    }
}